//
//  MeHomeViewController.m
//  seer
//
//  Created by Lin Eidan on 14-5-29.
//  Copyright (c) 2014年 haomee. All rights reserved.
//

#import "MeHomeViewController.h"
#import "LoginViewController.h"
#import "PersonalInfoViewController.h"
#import "SystemInfoVC.h"
#import "MyLevelViewController.h"
#import "VipVC.h"
#import "DownloadDisplayViewController.h"
#import "SysSettingViewController.h"
#import "Header.h"
#import "config.h"

@interface MeHomeViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
@property (strong, nonatomic) IBOutlet UIView *userNameBgView;
@property (strong, nonatomic) IBOutlet UILabel *userNameLabel;

@property (strong, nonatomic) IBOutlet UIImageView *headPicImageView;
@property (strong, nonatomic) IBOutlet UIImageView *headerPicVipCircleView;
@property (strong, nonatomic) IBOutlet UIImageView *headerPicVipBottmView;

@property (strong, nonatomic) IBOutlet UIImageView *campImageView;
@property (assign, nonatomic) float campImageViewDefaultHeight;

@property (strong, nonatomic) IBOutlet UIButton *loginBtn;

@property (strong, nonatomic) IBOutlet UIView *medalBgView;
@property (strong, nonatomic) IBOutlet UIImageView *leftMedalImageView;
@property (strong, nonatomic) IBOutlet UIImageView *middleMedalImageView;
@property (strong, nonatomic) IBOutlet UIImageView *rightMedalImageView;

@property (strong, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UIButton *sysInfoBtn;
@property (weak, nonatomic) IBOutlet UIButton *getWYBtn;

@property (weak, nonatomic) IBOutlet UILabel *coinLabel;

//faker View
@property (strong, nonatomic) IBOutlet UIView *fakerBottomView;

@end

@implementation MeHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initUI];
    // Do any additional setup after loading the view from its nib.
}

-(void)initUI{
    if (isiOS6) {
        self.myScrollView.top = -20;
        self.myScrollView.height +=20;
    }
    
    self.fakerBottomView.top = self.campImageView.bottom;
    [self.myScrollView addSubview:self.fakerBottomView];
    
    self.bottomView.top = self.campImageView.bottom;
    self.myScrollView.contentHeight = (self.bottomView.bottom > (self.myScrollView.height+1) ? self.bottomView.bottom :self.myScrollView.height+1);
    [self.myScrollView addSubview:self.bottomView];
    
    
    self.medalBgView.top = self.loginBtn.top;
    self.medalBgView.left = (self.myScrollView.width - self.medalBgView.width)/2;
    UIImage *star = [UIImage imageNamed:@"me_star.png"];
    self.leftMedalImageView.backgroundColor = [UIColor colorWithPatternImage:star];
    self.middleMedalImageView.backgroundColor = [UIColor colorWithPatternImage:star];
    self.rightMedalImageView.backgroundColor = [UIColor colorWithPatternImage:star];
    
    [self.myScrollView addSubview:self.medalBgView];
    
    self.headPicImageView.layer.cornerRadius = self.headPicImageView.width/2;
    self.headPicImageView.layer.masksToBounds = YES;
    self.headPicImageView.clipsToBounds = YES;
    
    self.campImageViewDefaultHeight = self.campImageView.height;
    self.loginBtn.layer.cornerRadius = 3;
    
    
}

-(void)handleTheTrueView{
    float bottom ;
    if ([[kHandle sharedInstance] isShowTrueView]) {
        self.bottomView.hidden = NO;
        self.fakerBottomView.hidden = YES;
        bottom = self.bottomView.bottom;
    }else{
        self.bottomView.hidden = YES;
        self.fakerBottomView.hidden = NO;
        bottom = self.fakerBottomView.bottom;
    }
     self.myScrollView.contentHeight = (bottom > (self.myScrollView.height+1) ? bottom :self.myScrollView.height+1);
}

-(void)viewWillAppear:(BOOL)animated{
    [self handleTheTrueView];
    
    UserObj *userObj = [UserObj sharedInstance];
   
    if (userObj.isLogin) {
        self.loginBtn.hidden = YES;
        self.userNameBgView.hidden = NO;
        self.medalBgView.hidden = NO;
        
        [self refreshTheUIWith:userObj];
        NSString *url = [NSString stringWithFormat:@"%@personCenter&uid=%@&ak=%@&pf=2",API_BASE,userObj.uid,userObj.accessKey];
        [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            if (isSuccess) {
                NSDictionary *dic = responseObj;
                
                userObj.username =  IsNull([dic objectForKey:@"username"]) ? DefaultUserName : [dic objectForKey:@"username"];
                userObj.headId = IsNull([dic objectForKey:@"head_id"]) ? DefaultUserHeaderId : [dic objectForKey:@"head_id"];
                userObj.headPicSrc = IsNull([dic objectForKey:@"pic"]) ? DefaultUserHeaderPic : [dic objectForKey:@"pic"];
                userObj.campPicSrc = IsNull([dic objectForKey:@"camp_pic"]) ? DefaultUserCampPic : [dic objectForKey:@"camp_pic"];
                userObj.phoneNum = [dic objectForKey:@"mobile"];
                userObj.campId = IsNull([dic objectForKey:@"camp_id"]) ? DefaultUserCampId : [dic objectForKey:@"camp_id"];
                userObj.qqId = [dic objectForKey:@"qq_id"];
                userObj.qqNickName = [dic objectForKey:@"qq_nickname"];
                userObj.sinaId = [dic objectForKey:@"sinawb_id"];
                userObj.sinaNickName = [dic objectForKey:@"sinawb_nickname"];
                userObj.sysMessageCount = [[dic objectForKey:@"sysmsg_count"] intValue];
                userObj.medalCount = [[dic objectForKey:@"medal_count"] intValue];
                
                userObj.lastSysMessageCount +=userObj.sysMessageCount;
                userObj.lastMedalCount += userObj.medalCount;
                
                NSDictionary *vip = [dic objectForKey:@"vip"];
                userObj.vipStartDate = [vip objectForKey:@"start_date"];
                userObj.vipOverData = [vip objectForKey:@"over_date"];
                userObj.coins = [[vip objectForKey:@"days"] intValue];
                userObj.isVip = [[vip objectForKey:@"flag"] boolValue];
               
                
                NSMutableArray *temp = [NSMutableArray array];
                for (NSDictionary *mDic in [dic objectForKey:@"medals"]) {
                    MyLevel *levelObj = [[MyLevel alloc] initWithType:[mDic objectForKey:@"type"] picUrl:[mDic objectForKey:@"pic"] name:[mDic objectForKey:@"name"] reason:@""];
                    [temp addObject:levelObj];
                }
                userObj.medalsDisplayArray = (NSArray *)temp;
                
               [userObj saveUserToLocal];
               
                [self showRedCircle];
                [self refreshTheUIWith:userObj];
                [self showOrHideCoins];
            }else{
                
                
            }
        }];
    }else{
        self.userNameBgView.hidden = YES;
        self.loginBtn.hidden = NO;
        self.headPicImageView.image = [UIImage imageNamed:DefaultUserHeaderPic];
        self.campImageView.image = [UIImage imageNamed:DefaultUserCampPic];
        self.medalBgView.hidden = YES;
        [self headerDisplayNormal];
        [self hideRedCircle];
        [self showOrHideCoins];
    }
   
}

#pragma mark - 显示小红点
-(void)showRedCircle
{
    [self hideRedCircle]; //显示前先清掉之前的
    [Common addRedCircleForView:self.sysInfoBtn andPosition:CGRectMake(10, 5, 32, 32) andCounts:[[UserObj sharedInstance] lastSysMessageCount]];
    [Common addRedCircleForView:self.getWYBtn andPosition:CGRectMake(10, 5, 32, 32) andCounts:[[UserObj sharedInstance] lastMedalCount]];
}

-(void)hideRedCircle
{
    UIView* view1 = [self.sysInfoBtn viewWithTag:10000];
    if(view1)
    {
        [view1 removeFromSuperview];
    }
    
    UIView* view2 = [self.getWYBtn viewWithTag:10000];
    if(view2)
    {
        [view2 removeFromSuperview];
    }

}

#pragma mark - 显示魁拔币
-(void)showOrHideCoins
{
    if([[UserObj sharedInstance] isLegalVip])
    {
        if([[UserObj sharedInstance] coins])
        {
            self.coinLabel.hidden = NO;
            self.coinLabel.text = [NSString stringWithFormat:@"(会员截止日期:%@)",[[UserObj sharedInstance] vipOverData]];
        }
        
        else{
            self.coinLabel.hidden = YES;
        }
    }
    else
    {
        self.coinLabel.hidden = YES;
    }
}

-(void)refreshTheUIWith:(UserObj *)userObj{
    self.userNameLabel.text = userObj.username;
    
    if ([userObj.headPicSrc rangeOfString:@"http://"].location != NSNotFound && userObj.headPicSrc) {  //如果是网络地址，先取。
        [[AFGetData sharedInstance] initSDWebImage:[UserObj sharedInstance].headPicSrc andTrueImageView:self.headPicImageView andPlaceholderImage:nil];
    }else{
        self.headPicImageView.image = [UIImage imageNamed:DefaultUserHeaderPic];
    }
    
    if (userObj.isVip) {
        self.headerPicVipBottmView.hidden = NO;
        self.headerPicVipCircleView.hidden = NO;
        self.headPicImageView.layer.borderWidth = 0;
    }else{
        [self headerDisplayNormal];
    }
    
    if ([userObj.campPicSrc rangeOfString:@"http://"].location != NSNotFound && userObj.campPicSrc) {  //如果是网络地址，先取。
        [[AFGetData sharedInstance] initSDWebImage:userObj.campPicSrc andTrueImageView:self.campImageView andPlaceholderImage:nil];
    }else{
        self.campImageView.image = [UIImage imageNamed:DefaultUserCampPic];
    }
    
    [self handleTheMedalDisplayWithArray:userObj.medalsDisplayArray];
}


-(void)headerDisplayNormal{
    self.headerPicVipBottmView.hidden = YES;
    self.headerPicVipCircleView.hidden = YES;
    self.headPicImageView.layer.borderColor = RGB(210, 210, 210).CGColor;
    self.headPicImageView.layer.borderWidth = 2;
}

-(void)handleTheMedalDisplayWithArray:(NSArray *)medalArray{
    if (medalArray.count == 0 || medalArray == nil) {
        self.medalBgView.hidden = YES;
    }else{
        self.medalBgView.hidden = NO;
        if (medalArray.count == 1) {
            self.leftMedalImageView.hidden = YES;
            self.rightMedalImageView.hidden = YES;
            self.middleMedalImageView.hidden = NO;
            self.middleMedalImageView.left = 80;
            MyLevel *obj = [medalArray objectAtIndex:0];
            [[AFGetData sharedInstance] initSDWebImage:obj.picUrl andTrueImageView:self.middleMedalImageView andPlaceholderImage:nil];
        }else if (medalArray.count == 2){
            self.leftMedalImageView.hidden = NO;
            self.rightMedalImageView.hidden = YES;
            self.middleMedalImageView.hidden = NO;
            self.leftMedalImageView.left = 40;
            self.middleMedalImageView.left = 120;
            MyLevel *obj = [medalArray objectAtIndex:0];
            [[AFGetData sharedInstance] initSDWebImage:obj.picUrl andTrueImageView:self.leftMedalImageView andPlaceholderImage:nil];
            MyLevel *obj1 = [medalArray objectAtIndex:1];
            [[AFGetData sharedInstance] initSDWebImage:obj1.picUrl andTrueImageView:self.middleMedalImageView andPlaceholderImage:nil];
        }else{
            self.leftMedalImageView.hidden = NO;
            self.rightMedalImageView.hidden = NO;
            self.middleMedalImageView.hidden = NO;
            self.leftMedalImageView.left = 20;
            self.middleMedalImageView.left = 80;
            self.rightMedalImageView.left = 140;
            MyLevel *obj = [medalArray objectAtIndex:0];
            [[AFGetData sharedInstance] initSDWebImage:obj.picUrl andTrueImageView:self.leftMedalImageView andPlaceholderImage:nil];
            MyLevel *obj1 = [medalArray objectAtIndex:1];
            [[AFGetData sharedInstance] initSDWebImage:obj1.picUrl andTrueImageView:self.middleMedalImageView andPlaceholderImage:nil];
            MyLevel *obj2 = [medalArray objectAtIndex:2];
            [[AFGetData sharedInstance] initSDWebImage:obj2.picUrl andTrueImageView:self.rightMedalImageView andPlaceholderImage:nil];
        }
    }
    
}



#pragma -mark xib clicked
- (IBAction)login:(id)sender {
    LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (IBAction)goToSysInfo:(id)sender {

    if([[UserObj sharedInstance] isLegalLogin])
    {
            for (UIView* mView in self.sysInfoBtn.subviews) {
                if(mView.tag == 10000)
                {
                    [mView removeFromSuperview];
                }
            }
        [[UserObj sharedInstance] setLastSysMessageCount:0];
        [[UserObj sharedInstance] saveUserToLocal];
        
        SystemInfoVC* infoVC = [[SystemInfoVC alloc]initWithNibName:@"SystemInfoVC" bundle:nil];
        [self.navigationController pushViewController:infoVC animated:YES];
    }
    else{
        [PopTips tips:self.view Msg:NotifyLoginFirst];
    }

}

- (IBAction)goToWenYao:(id)sender {
    if([[UserObj sharedInstance] isLegalLogin])
    {
        for (UIView* mView in self.getWYBtn.subviews) {
            if(mView.tag == 10000)
            {
                [mView removeFromSuperview];
            }
        }
        [[UserObj sharedInstance] setLastMedalCount:0];
        [[UserObj sharedInstance] saveUserToLocal];
       
        
    MyLevelViewController *myLevelVC = [MyLevelViewController new];
    myLevelVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
   [self.navigationController pushViewController:myLevelVC animated:YES];
    }
    else{
         [PopTips tips:self.view Msg:NotifyLoginFirst];
    }
}

- (IBAction)goToVip:(id)sender {
    VipVC* vipVC = [[VipVC alloc]initWithNibName:@"VipVC" bundle:nil];
    [self.navigationController pushViewController:vipVC animated:YES];
}

- (IBAction)goToDownload:(id)sender {
    DownloadDisplayViewController *downloadDisplayVC = [[DownloadDisplayViewController alloc] initWithNibName:@"DownloadDisplayViewController" bundle:nil];
    [self.navigationController pushViewController:downloadDisplayVC animated:YES];

}

- (IBAction)goToSysManager:(id)sender {
    SysSettingViewController *sysVC = [[SysSettingViewController alloc] init];
    [self.navigationController pushViewController:sysVC animated:YES];

}

- (IBAction)goToShare:(id)sender {

    [kApp initShareViewWithUrl:ShareUrl andWithTitle:ShareTitle andWithInfo:NotifyRecommendShare andWithImageUlr:ShareImageUrl andIsSuccess:^(BOOL isSuccess) {
        if(isSuccess)
        {
            [PopTips tips:kApp.rootNav.view Msg:NotifyShareSuccess];
        }
        else{
           [PopTips tips:kApp.rootNav.view Msg:NotifyShareError];
        }
    }];

}

- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma -mark UIScrollView

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset  = scrollView.contentOffset.y;
    if (yOffset > -self.campImageViewDefaultHeight && yOffset <=0) {
        self.campImageView.height = -yOffset + self.campImageViewDefaultHeight;
        self.campImageView.top = yOffset;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
